﻿var scEditor = null;
var scTool = null;

RadEditorCommandList["ColorboxLink"] = function (commandName, editor, args) {
    var d = Telerik.Web.UI.Editor.CommandList._getLinkArgument(editor);
    Telerik.Web.UI.Editor.CommandList._getDialogArguments(d, "A", editor, "DocumentManager");

    var html = editor.getSelectionHtml();

    scEditor = editor;

    editor.showExternalDialog(
		"/sitecore/shell/default.aspx?xmlcontrol=RichText.ColorboxLink&la=" + scLanguage,
		null, //argument
		500,
		180,
		scColorboxLinkCallback, //callback
		null, // callback args
		"Colorbox",
		true, //modal
		Telerik.Web.UI.WindowBehaviors.Close, // behaviors
		false, //showStatusBar
		false //showTitleBar
	  );
};

function scColorboxLinkCallback(sender, returnValue) {
    if (!returnValue) {
        return;
    }

    var d = scEditor.getSelection().getParentElement();

    if ($telerik.isFirefox && d.tagName == "A") {
        d.parentNode.removeChild(d);
    } else {
        scEditor.fire("Unlink");
    }

    var text = scEditor.getSelectionHtml();

    if (text == "" || text == null || ((text != null) && (text.length == 15) && (text.substring(2, 15).toLowerCase() == "<p>&nbsp;</p>"))) {
        text = 'Text';
    }
    else {
        // if selected string is a full paragraph, we want to insert the link inside the paragraph, and not the other way around.
        var regex = /^[\s]*<p>(.+)<\/p>[\s]*$/i;
        var match = regex.exec(text);
        if (match && match.length >= 2) {
            scEditor.pasteHtml("<p><a href=\"#\" class=\"" + returnValue.colorboxClass + "\">" + match[1] + "</a></p>", "DocumentManager");
            return;
        }
    }

    scEditor.pasteHtml("<a href=\"#\" class=\"" + returnValue.colorboxClass + "\">" + text + "</a>", "DocumentManager");
}